<script setup lang='ts'>
import { ref,reactive,onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import HandheldInfoTable from './ui/HandheldInfoTable.vue'
import {
  GetHarbor,
  GetCompany
} from '@/api/http'
import {
  GetEquipmentList,
  AddEquipment,
  EditEquipment,
  DeleteEquipment
} from '@/api/publicApi'
// 定义变量
const time = ref('first')

// 弹框
const dialogVisible = ref(false)

// 弹框表单
const formData = reactive({
  name: '',
  code: '',
  portCode: '',
  isAvailable: '',
  description: '',
  companyCode: ''
})
// 港口信息
const portList:any = ref([])
// 公司信息
const companyList: any = ref([])

// ref
const handheldInfoTableRef = ref()

// 选中的信息
let updateItem:any = reactive({})

// 是否未编辑
const isUpdate = ref(false)

// 表单验证
const validPassword = (rule, value, callback) => {
  // 匹配字符串格式：字母大小写  数字  下划线 横线 正反斜线
  let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_ /\\//\-/\\]+$/
  // 
  if (!reg.test(value)) {
    callback(new Error('编号格式不正确，含有特殊字符!'))
  }
}

// 表单验证
const rules = reactive({
  name: [ { required: true, message: '名称不能为空' } ],
  code: [
    { required: true, message: '编号不能为空' },
    { validator: validPassword, trigger: 'blur' }
  ],
  portCode: [
    {
      required: true,
      message: '请选择港口',
      trigger: 'change'
    }
  ],
  companyCode: [
    {
      required: true,
      message: '请选择公司',
      trigger: 'change'
    }
  ],
  barWheelMachineCode: [
    {
      type: 'date',
      required: true,
      message: '请选择堆取料机',
      trigger: 'change'
    }
  ],
  deviceCode: [
    {
      type: 'date',
      required: true,
      message: '请选择设备',
      trigger: 'change'
    }
  ]
})

// 定义函数
onMounted(() => {
  getPortData()
})

const showDialog = (num:number,row?:any) => {
  if(num) {
    isUpdate.value = true
    console.log('修改信息---->',row)
    updateItem = {}
    updateItem = { ...row }
    formData.name = row.name
    formData.code = row.code
    formData.isAvailable = row.isAvailable
    formData.description = row.noAvailableInfo
  } else {
    isUpdate.value = false
  }
  dialogVisible.value = true
}

// 获取港口\公司信息
const getPortData = async () => {
  portList.value = []
  let params = {
    SkipCount: (handheldInfoTableRef.value.pageInfo.pageNum - 1) * handheldInfoTableRef.value.pageInfo.pageSize,
    MaxResultCount: handheldInfoTableRef.value.pageInfo.pageSize
  }
  let res = await GetHarbor(params)
  if(res.success) {
    portList.value = [ ...res.result.items ]
  }
}
// 获取公司信息
const getCompanyData = async (e:any) => {
  formData.portCode = e
  companyList.value = []
  let res = await GetCompany({
    HarborCode: formData.portCode
  })
  companyList.value = [ ...res.result.items ]
}

// 确定 
const determine = async () => {
  let res
  if(isUpdate.value) {
    let data = {
      name: formData.name,
      isAvailable: formData.isAvailable,
      description: formData.description
    }
    res = await EditEquipment(data)
    if (res.success) {
      ElMessage({
        // message: `${res.message}`,
        message: '修改成功！',
        type: 'success'
      })
      handheldInfoTableRef.value.getHandheldInfoData()
      dialogVisible.value = false
    } else {
      ElMessage({
        // message: `${res.message}`,
        message: '修改失败！',
        type: 'error'
      })
    }
  }else {
    console.log('确定新增------->')
    res = await AddEquipment(formData)
    if (res.success) {
      ElMessage({
        // message: `${res.message}`,
        message: '添加成功！',
        type: 'success'
      })
      handheldInfoTableRef.value.getHandheldInfoData()
      dialogVisible.value = false
    } else {
      ElMessage({
        // message: `${res.message}`,
        message: '添加失败！',
        type: 'error'
      })
    }
  }
}

// 取消
const cancellation = () => {
  console.log('取消------->')
  dialogVisible.value = false
}

// 关闭弹框
const closeDialog = () => {
  formData.name = ''
  formData.code = ''
  formData.isAvailable = ''
  formData.description = ''
  formData.portCode = ''
  formData.companyCode = ''
}
</script>

<template>
  <div class="handheld-info-main-box">
    <div
      class="add-sensor-btn custom-button"
      @click="showDialog(0)"
    >
      添加手持传感器
    </div>
    <div class="table-box">
      <HandheldInfoTable
        ref="handheldInfoTableRef"
        :show-dialog="showDialog"
      />
    </div>
    <div class="dialog-box">
      <el-dialog
        v-model="dialogVisible"
        width="580"
        :title="isUpdate ? '修改信息' : '添加信息'"
        @close="closeDialog"
      >
        <template #default>
          <div class="form-box">
            <el-form
              class="formStyle"
              :model="formData"
              :rules="rules"
              label-width="130px"
            >
              <el-form-item
                label="名称:"
                prop="name"
              >
                <el-input v-model="formData.name" />
              </el-form-item>
        
              <el-form-item
                label="编号:"
                prop="code"
              >
                <el-input
                  v-model="formData.code"
                  :disabled="isUpdate"
                />
              </el-form-item>
              <el-form-item
                v-if="!isUpdate"
                prop="portCode"
                label="港口"
              >
                <el-select
                  v-model="formData.portCode"
                  class="handheld-info-select"
                  placeholder="请选择"
                  @change="getCompanyData"
                >
                  <el-option
                    v-for="item in portList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                v-if=" !isUpdate && formData.portCode"
                label="所属公司"
                prop="companyCode"
              >
                <el-select
                  v-model="formData.companyCode"
                  class="handheld-info-select"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in companyList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="是否可用">
                <el-radio-group v-model="formData.isAvailable">
                  <el-radio :label="true">
                    可用
                  </el-radio>
                  <el-radio :label="false">
                    不可用
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label="原因描述:"
                prop="noAvailableInfo"
              >
                <el-input v-model="formData.description" />
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancellation">
            取 消
          </el-button>
          <el-button
            @click="determine"
          >
            确 定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped lang=scss>
.handheld-info-main-box {
  width: 100%;
  height: 100%;
  padding-top: 10px;
  background-color: #fff;

  .add-sensor-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 150px;
    height: 40px;
    margin-left: 15px;
  }

  .table-box {
    width: 100%;
    height: 100%;
    margin-top: 15px;
    padding: 0 15px;

    /* border: 1px solid red; */
  }
}
</style>
<style lang="scss">
.form-box {
  padding-right: 10%;
  padding-left: 10px;

  /* border: 1px solid red; */
}

.handheld-info-select {
  width: 100%;
}
</style>